package com.leyou.user.controller;

import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.print.attribute.standard.JobOriginatingUserName;
import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author linzx
 * @date 2020/3/29
 */
@RestController
@RequestMapping()
public class UserController {
    @Autowired
    private UserService userService;

    /**
     *校验手机和用户名是否为不相同的
     * @param data
     * @param type
     * @return
     */
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data , @PathVariable("type") Integer type) {

        return ResponseEntity.ok(userService.checkData(data,type));
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("send")
    public ResponseEntity<Void> sendCode(@RequestParam("phone") String phone) {
        userService.sendCode(phone);
        return ResponseEntity.noContent().build();
    }
    /**
     * 注册
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result , @RequestParam("code") String code) {
        if (result.hasErrors()) {
            throw new RuntimeException(result.getFieldErrors().stream()
                    .map(e -> e.getDefaultMessage()).collect(Collectors.joining("|")));
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("query")
    public ResponseEntity<User> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    ) {
        return ResponseEntity.ok(userService.login(username,password));
    }

}
